//
//  FCCustomerRelationRequest.m
//  customerRelation_Example
//
//  Created by 陈文斌 on 2019/2/17.
//  Copyright © 2019 64912907. All rights reserved.
//

#import "FCCustomerRelationRequest.h"
#import "Define.h"
#import "FCModel2Json.h"
#import "SVProgressHUD.h"
#import "commonUseHeader.h"
#import "FCRelationListModel.h"
#import "FCRelationBindRequestViewController.h"
#import "FCCustomerRelationRequestTool.h"
#import "CustomerRelationHeader.h"
#import "FCBaseTool.h"
#import "FCAlertViewController.h"
#import "FCPermissRequest.h"

@implementation FCCustomerRelationRequest


#define GoDealCode @"crmsupplyrelation:go_deal_relation"
#define GoCmpCode @"crmsupplyrelation:go_cmp_verify"
#define TypeZero @"crmsupplyrelation:type_zero"
#define TypeHasRelations @"crmsupplyrelation:type_has_relations"

/**
 * 获取关系类型
 */
+ (void)getCrmSupplyRelationTypeWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool getCrmSupplyRelationTypeQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Args:args success:success failure:failure];
}

/**
 * 获取关系请求列表
 */
+ (void)getRelationRequestsWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool getRelationRequestsQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Args:args success:success failure:failure];
}

/**
 * 添加上下游关系
 */
+ (void)addRelationRequestsWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool addRelationRequestsQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Args:args success:success failure:failure];
}
/**
 * 获取关系详情
 */
+ (void)getRelationDetailWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool getRelationDetailQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Args:args success:success failure:failure];
}
/**
 * 编辑关系信息
 */
+ (void)editRelationWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool editRelationQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Args:args success:success failure:failure];
}

/**
 * 删除关系信息
 */
+ (void)deleteRelationRequestWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool deleteRelationRequestQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Args:args success:success failure:failure];
}

/**
 * 处理关系
 */
+ (void)dealRelationRequestWithArgs:(NSDictionary *)args vc:(UIViewController *)vc success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool dealRelationRequestQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Args:args VC:vc isShowErrorInfo:YES success:success failure:failure];
}

/**
 * 获取工作组员工
 */
+ (void)getWorkGroupEmployeeWithVariables:(NSDictionary *)variables success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool getWorkGroupEmployeeQuery];
    [self graphqlRequestWithUrl:API_cloud_Url Query:query Variables:variables success:success failure:failure];
}

/**
 部门列表
 
 @param companyId 企业标识
 @param param 其他限制条件//可传空
 */
+(void)getCompanyCompanydepartmentsWithCompanyId:(NSString *)companyId orOtherParam:(NSMutableDictionary *)param success:(void (^)(NSArray<FCCompanyDepartmentModel *> *))success failure:(void (^)(NSError *))failure{
    NSMutableString *requestURL = [[NSString stringWithFormat:@"%@/Companydepartments/CompanyDepartment/List?Take=100&CompanyId=%@&DepartmentTree=true&meId=%@&fields=nodep,Children",APIurlv11,companyId,[FCEmployeeModel getMinieCompanyId]] mutableCopy];
    if (param) {
        [requestURL appendFormat:@"&%@",[FCModel2Json getUrlGet2Dic:param]];
    }
    [FCBaseTool getWithUrl:requestURL param:nil resultClass:[FCCompanyDepartmentModel class] keyValues:NO success:success failure:failure];
    
}

/**
 自己的企业的职员列表(包含未审核的企业)
 */
+ (void)myEmployeesListWithParam:(NSMutableDictionary *)param success:(void (^)(NSMutableArray *result))success failure:(void (^)(NSError *error))failure
{
    NSString *requestURL = [NSString stringWithFormat:@"%@/My/Employees",APIurlv11];
    [FCBaseTool getWithUrl:requestURL param:param resultClass:[FCEmployeeModel class] keyValues:NO success:success failure:failure];
}

/**
 * 根据全称和所有者电话获取企业
 */
+ (void)getCompanyInfoWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool getCompanyQuery];
    [self graphqlRequestWithUrl:@"/gqlgateway/graphql" Query:query Args:args success:success failure:failure];
}

/**
 * 添加或更新关系类型，更新需要传关系类型Id
 */
+ (void)addOrUpdateRelationTypeWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool addOrUpdateRelationTypeQuery];
    [self graphqlRequestWithUrl:@"/gqlgateway/graphql" Query:query Args:args success:success failure:failure];
}

/**
 * 删除关系类型
 */
+ (void)deleteRelationTypeWithArgs:(NSDictionary *)args vc:(UIViewController *)vc success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool deleteRelationTypeQuery];
    [self graphqlRequestWithUrl:@"/gqlgateway/graphql" Query:query Args:args VC:vc isShowErrorInfo:NO success:success failure:failure];
}

/**
 * 关系类型排序
 */
+ (void)sortRelationTypeWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool sortRelationTypeQuery];
    [self graphqlRequestWithUrl:@"/gqlgateway/graphql" Query:query Args:args success:success failure:failure];
}

/**
 * 检测当前职员是否仅是类型负责人
 */
+ (void)relationOnlyTypeManagerWithArgs:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSString *query = [FCCustomerRelationRequestTool relationOnlyTypeManagerQuery];
    [self graphqlRequestWithUrl:@"/gqlgateway/graphql" Query:query Args:args success:success failure:failure];
    
}

/**
 * 权限验证
 */
- (void)getPermissionWithManyCode:(NSArray *)code andReturnBlock:(void (^)(NSArray<FCPermissSubCellModel *> *))success{
    NSMutableString *str=[NSMutableString new];
    for (NSString *c in code) {
        [str appendFormat:@"type = '%@' or ",c];
    }
    if (str.length>3) {
        str =[str substringToIndex:str.length-3];
    }
    NSArray *arr=[saveSandBox getDataBaseWithClass:[FCPermissSubCellModel class] andLimitType:str];
    if (arr.count==code.count) {
        if (success) {
            success(arr);
            return;
        }
    }
    [FCPermissRequest checkPermissWithParams:@{@"ids":code} success:^(NSArray *resultObj) {
        [SVProgressHUD dismiss];
        for (FCPermissSubCellModel *m in resultObj) {
            [saveSandBox saveDataBaseClass:[FCPermissSubCellModel class] andObject:m.mj_keyValues orType:m.fullCode andOther:m.code];
        }
        if (success) {
            success(resultObj);
        }
    } failure:^(NSError *error) {
        
        [SVProgressHUD dismiss];
        
    }];
}


/**
 * GraphQL请求 args
 */
+ (void)graphqlRequestWithUrl:(NSString *)requestURL Query:(NSString *)query Args:(NSDictionary *)args success:(successBlock)success failure:(errorBlock)failure{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"query"] = query;
    params[@"variables"] = @{@"args": args};
    WJCWeakSelf
    [self post:[NSString stringWithFormat:@"%@",API_cloud_Url] params:params success:success failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        if (failure) {
            failure(error);
        }
    }];
}

/**
 * GraphQL请求 variables
 */
+ (void)graphqlRequestWithUrl:(NSString *)requestURL Query:(NSString *)query Variables:(NSDictionary *)variables success:(successBlock)success failure:(errorBlock)failure{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"query"] = query;
    params[@"variables"] = variables;
    WJCWeakSelf
    [self post:API_cloud_Url params:params success:success failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        if (failure) {
            failure(error);
        }
    }];
}


/**
 *GraphQL请求 带VC
 */
+ (void)graphqlRequestWithUrl:(NSString *)requestURL Query:(NSString *)query Args:(NSDictionary *)args VC:(UIViewController *)vc isShowErrorInfo:(BOOL)isShowErrorInfo success:(successBlock)success failure:(errorBlock)failure{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"query"] = query;
    params[@"variables"] = @{@"args": args};
    WJCWeakSelf
    if (isShowErrorInfo) {
        [self post:API_cloud_Url params:params success:success failure:^(NSError *error) {
            [SVProgressHUD dismiss];
            if (failure) {
                failure(error);
                [self handRrrorWithError:error vc:vc];
            }
        }];
    } else {
        AFHTTPSessionManager *manager = [self getAFManager];
        manager.requestSerializer.timeoutInterval = 8.f;
        [manager POST:[NSString stringWithFormat:@"%@",API_cloud_Url] parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
            [self handRrrorWithError:error vc:vc];
        }];
    }
}

/**
 * 错误信息过滤处理
 */
+ (void)handRrrorWithError:(NSError *)error vc:(UIViewController *)vc{
    WJCWeakSelf
    if(error.userInfo[@"com.alamofire.serialization.response.error.data"]){
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:&error];
        if (dic) {
            if (dic[@"errors"]) {
                NSArray *errorArr = dic[@"errors"];
                if (errorArr.count > 0 && errorArr[0][@"extensions"]) {
                    NSDictionary *extensionsDic = errorArr[0][@"extensions"];
                    // 跳转到关系详情页
                    if([extensionsDic[@"code"] isEqualToString:GoDealCode]){
                        [FCCustomerRelationRequest getRelationDetailWithArgs:@{@"id": extensionsDic[@"data"][@"id"]} success:^(id resultObj) {
                            FCRelationModel *relationModel = [FCRelationModel mj_objectWithKeyValues:resultObj[@"data"][@"crmSupplyRelationGet"]];
                            FCRelationBindRequestViewController *relationBindRequestVC = [[FCRelationBindRequestViewController alloc] init];
                            relationBindRequestVC.relation = relationModel;
                            [vc.navigationController pushViewController:relationBindRequestVC animated:YES];
                            [SVProgressHUD dismiss];
                        } failure:^(NSError *error) {
                            [SVProgressHUD dismiss];
                        }];
                    }
                    // 跳转到企业认证
                    if([extensionsDic[@"code"] isEqualToString:GoCmpCode]){
                        [vc pushAppControllerWithControllerName:@"FCAuthenticationViewController" andObjectData:@{} andTitle:customerRelationLocaChanged(@"company_card_real_authentic", @"实名认证")];
                    }
                    // 至少保留一个类型
                    if ([extensionsDic[@"code"] isEqualToString:TypeZero]) {
                        NSString *message = errorArr[0][@"message"];
                        FCAlertViewController *controller=[[FCAlertViewController alloc] initWithTitle:message andSubTitle:@"" andAlertType:FCAlertTxt];
                        FCAlertAction *commitAction=[FCAlertAction actionWithTitle:customerRelationLocaChanged(@"好的，我了解了",@"好的，我了解了") style:FCAlertActionDefault handler:^(FCAlertAction *action) {
                            
                        }];
                        [controller addAction:commitAction];
                        
                        [vc presentViewController:controller animated:YES completion:nil];
                    }
                    // 类型下有关系数据
                    if ([extensionsDic[@"code"] isEqualToString:TypeHasRelations]) {
                        NSString *message = errorArr[0][@"message"];
                        FCAlertViewController *controller=[[FCAlertViewController alloc] initWithTitle:message andSubTitle:@"" andAlertType:FCAlertTxt];
                        FCAlertAction *commitAction=[FCAlertAction actionWithTitle:customerRelationLocaChanged(@"好的，我了解了",@"好的，我了解了") style:FCAlertActionDefault handler:^(FCAlertAction *action) {
                            
                        }];
                        [controller addAction:commitAction];
                        
                        [vc presentViewController:controller animated:YES completion:nil];
                    }
                    
                }
            }
        }
    }
}

@end
